var uuid = function () {
    var uuid = '';
    for (var i = 1; i <= 32; i++) {
        var n = Math.floor(Math.random() * 16.0).toString(16);
        uuid += n;
    }
    return uuid;
};

function getUrlParam(href) {
    if (href.indexOf('?') > -1) {
        let paramStr = href.split('?')[1]
        let paramArr = paramStr.split('&')
        let returnObj = {}
        for (let i = 0; i < paramArr.length; i++) {
            let paramItem = paramArr[i].split('=')
            returnObj[paramItem[0]] = paramItem[1]
        }
        return returnObj
    } else {
        return {}
    }
}

function QueryTask(options) {
    var urlOptions = getUrlParam(options.url);
    var CallbackAD = 'jscallback' + uuid();
    var url = options.url.split('?')[0];
    url += '/query';
    var optionsStr = '';
    optionsStr += '?PSCode=' + urlOptions.PSCode;
    optionsStr += '&BSCode=' + urlOptions.BSCode;
    optionsStr += '&appCode=' + urlOptions.appCode;
    optionsStr += '&appPass=' + urlOptions.appPass;
    optionsStr += '&f=json';
    optionsStr += '&where=' + options.where.replaceAll('%', '%25');
    optionsStr += '&returnGeometry=true';
    optionsStr += '&spatialRel=esriSpatialRelIntersects';
    optionsStr += '&' + encodeURI(`geometry={"rings":[${JSON.stringify(options.geometry)}],"spatialReference":{"wkid":4326}}`).replaceAll(':', '%3A').replaceAll(',', '%2C');
    optionsStr += '&geometryType=esriGeometryPolygon';
    optionsStr += '&inSR=4326';
    optionsStr += '&outFields=*';
    optionsStr += '&outSR=4326';
    optionsStr += '&callback=' + CallbackAD;
    return new Promise((resolve, reject) => {
        window[CallbackAD] = (result) => {
            resolve(result)
        }
        var JSONP = document.createElement("script");
        JSONP.type = "text/javascript";
        JSONP.src = url + optionsStr;
        document.getElementsByTagName("head")[0].appendChild(JSONP);
        setTimeout(() => {
            document.getElementsByTagName("head")[0].removeChild(JSONP)
        }, 500)
    });
}


export { QueryTask }
